<!--
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-11-21 17:13:52
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-02-21 11:44:19
 * @Description:
 *
-->

<template>
  <MyContainer class="container">
    <MyHeader class="header">
      <el-input
        v-model="searchKey"
        style="width: 200px; margin-right: 20px"
        size="medium"
        class="input"
        placeholder="请输入关键字进行过滤"
        clearable
        @clear="clearClick"
        @keyup.enter.native="queryClick"
      />
      <el-button
        size="medium"
        type="primary"
        @click="queryClick"
      >查询</el-button>
      <el-button size="medium" @click="resetClick">重置</el-button>
      <el-button
        size="medium"
        style="margin-left: auto"
        type="primary"
        icon="el-icon-refresh"
        :loading="syncLoading"
        @click="syncClick"
      >同步</el-button>
      <el-button
        size="medium"
        type="primary"
        :loading="btnLoadingBatchDel"
        plain
        @click="batchDeleteClick"
      >批量删除</el-button>
    </MyHeader>
    <MyMain class="main">
      <el-table
        v-loading="loading"
        class="common-table"
        :data="list"
        stripe
        header-cell-class-name="listHeaderCell"
        :header-cell-style="{ color: '#696969' }"
        @selection-change="handleSelectionChange"
      >
        <!-- 多选框 -->
        <el-table-column type="selection" width="60" />
        <el-table-column
          prop="name"
          label="区域名称"
          min-width="130"
          show-overflow-tooltip=""
        />
        <el-table-column
          prop="zoneNum"
          label="可用区数量"
          min-width="100"
          show-overflow-tooltip=""
        />
        <el-table-column
          prop="cloudProvider"
          label="云服务商"
          min-width="100"
          show-overflow-tooltip=""
        />
        <!-- <el-table-column
          prop="cloudAccountName"
          label="云账户名称"
          min-width="150"
          show-overflow-tooltip=""
        /> -->
        <el-table-column
          prop="status"
          label="状态"
          min-width="90"
          show-overflow-tooltip=""
        />
        <el-table-column
          prop="desc"
          label="描述"
          min-width="150"
          show-overflow-tooltip=""
        />
        <el-table-column
          prop="createBy"
          label="创建人"
          min-width="100"
          show-overflow-tooltip=""
        />
        <el-table-column prop="createDate" label="创建时间" width="170" />
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              style="height: 22px; line-height: 22px; padding: 0 10px"
              @click="editClick(scope.row)"
            >编辑</el-button>
            <el-popover
              :ref="`popover-delete-${scope.$index}`"
              placement="top"
              width="300"
              style="margin-left: 10px"
            >
              <p>是否确认删除该区域？</p>
              <div style="text-align: right; margin: 0">
                <el-button
                  size="mini"
                  type="text"
                  @click="
                    scope._self.$refs[
                      `popover-delete-${scope.$index}`
                    ].doClose()
                  "
                >取消</el-button>
                <el-button
                  type="primary"
                  size="mini"
                  @click="deleteClick(scope)"
                >确定</el-button>
              </div>
              <el-button
                slot="reference"
                type="danger"
                style="height: 22px; line-height: 22px; padding: 0 10px"
                size="mini"
              >删除</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="margin-top: 30px">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :page-sizes="[10, 15, 20]"
          :page-size="pageSize"
          :current-page.sync="pageNum"
          :total="totalCount"
          @current-change="changePage"
          @size-change="sizeChange"
        />
      </el-row>
    </MyMain>
    <!--编辑-->
    <el-dialog
      v-if="showDialog"
      class="create-dialog"
      :title="'修改区域配置'"
      :visible="showDialog"
      width="600px"
      top="15vh"
      :close-on-click-modal="false"
      @close="showDialog = false"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="auto">
        <el-form-item label="区域名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入区域名称"
            :disabled="true"
          />
        </el-form-item>
        <el-form-item label="可用区" prop="zone">
          <el-checkbox-group v-model="form.zone" class="checkbox">
            <el-checkbox
              v-for="(item, index) in zoneOptions"
              :key="index"
              :label="item.key"
            >{{ item.text }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input
            v-model="form.desc"
            placeholder="请输入描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="showDialog = false">取 消</el-button>
        <el-button
          type="primary"
          size="small"
          :loading="dialogConfirmLoading"
          @click="dialogConfirmClick"
        >确 定</el-button>
      </div>
    </el-dialog>
  </MyContainer>
</template>

<script>
import pagePermissionMixin from '@/views/mixin/pagePermission.js'
import pageQueryMixin from '@/views/mixin/pageQuery.js'
import MyContainer from '@/components/Layout/MyContainer.vue'
import MyHeader from '@/components/Layout/MyHeader.vue'
import MyMain from '@/components/Layout/MyMain.vue'
import {
  syncRegion,
  getRegionList,
  updateRegion,
  deleteRegion
} from '@/api/cn-resource'

export default {
  name: 'RegionMgmt',
  components: {
    MyContainer,
    MyHeader,
    MyMain
  },
  mixins: [pagePermissionMixin, pageQueryMixin],
  data() {
    return {
      selection: [],
      btnLoadingBatchDel: false, // 批量删除loading
      syncLoading: false, // 同步loading
      statusOptions: [
        {
          lable: '启用',
          value: '启用'
        },
        {
          lable: '停用',
          value: '停用'
        }
      ], // 状态
      zoneOptions: [], // 可用区
      // 校验规则
      form: {
        id: '',
        name: '',
        zone: [],
        status: '',
        desc: ''
      },
      rules: {
        name: [{ required: true, message: '请输入区域名称', trigger: 'blur' }],
        zone: [{ required: true, message: '请选择可用区', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      showDialog: false,
      dialogConfirmLoading: false // 确定loading
    }
  },
  created() {},
  methods: {
    /**
     * @description: 同步
     * @return {*}
     */
    syncClick() {
      this.syncLoading = true
      syncRegion({})
        .then((res) => {
          this.$message.success({
            message: '同步成功！',
            duration: '2000'
          })
          this.pageNum = 1 // 第一页
          this.getList() // 刷新数据
        })
        .finally(() => {
          this.syncLoading = false
        })
    },
    /**
     * @description: 确定
     * @return {*}
     */
    dialogConfirmClick() {
      // 校验
      this.$refs.form.validate((valid, obj) => {
        if (valid) {
          // 合法
          this.dialogConfirmLoading = true
          const zones = this.zoneOptions.map(item => {
            item.val = this.form.zone.includes(item.key)
            return item
          })
          updateRegion({
            id: this.form.id,
            status: this.form.status,
            desc: this.form.desc,
            zones: zones
          })
            .then((res) => {
              this.$message.success({
                message: '修改区域配置成功！',
                duration: '2000'
              })
              this.showDialog = false // 取消弹窗
              this.pageNum = 1 // 第一页
              this.getList() // 刷新数据
            })
            .finally(() => {
              this.dialogConfirmLoading = false
            })
        }
      })
    },
    /**
     * @description: 编辑
     * @return {*}
     */
    editClick(row) {
      this.$refs.form && this.$refs.form.resetFields() // 表单重置
      this.zoneOptions = row.zones || []
      const zone = []
      if (Array.isArray(row.zones)) {
        row.zones.forEach(element => {
          if (element.val) {
            zone.push(element.key)
          }
        })
      }
      this.form = {
        id: row.id,
        name: row.name,
        status: row.status,
        desc: row.desc,
        zone: zone
      }
      this.showDialog = true // 展示
    },
    /**
     * @description: 选择
     * @param {*} selection
     * @return {*}
     */
    handleSelectionChange(selection) {
      this.selection = selection
    },
    /**
     * @description: 批量删除
     * @return {*}
     */
    batchDeleteClick() {
      if (this.selection.length === 0) {
        this.$message.warning({
          message: '请先选择区域',
          duration: '2000'
        })
        return
      }
      const ids = []
      for (const item of this.selection) {
        ids.push(item.id)
      }
      this.$confirm('是否确认批量删除当前已选中的区域？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        this.btnLoadingBatchDel = true
        deleteRegion({ ids })
          .then((res) => {
            this.selection = []
            this.$message.success({
              message: '批量删除成功',
              duration: '2000'
            })
            if (this.list.length === 1) {
              // 当前页只有一条数据时 删除完刷新上一页数据
              this.pageNum = Math.max(this.pageNum - 1, 1)
            }
            this.getList() // 请求数据
          })
          .finally(() => {
            this.btnLoadingBatchDel = false
          })
      })
    },
    /**
     * @description: 删除
     * @param {*} row
     * @param {*} index
     * @return {*}
     */
    deleteClick(scope) {
      const row = scope.row
      deleteRegion({
        ids: [row.id]
      }).then((res) => {
        scope._self.$refs[`popover-delete-${scope.$index}`].doClose() // 取消popover
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          // 当前页只有一条数据时 删除完刷新上一页数据
          this.pageNum = Math.max(this.pageNum - 1, 1)
        }
        this.getList() // 请求数据
      })
    },
    /**
     * @description: 获取列表
     * @return {*}
     */
    getList() {
      this.handleRequestAndResp(getRegionList, {
        keyword: this.searchKey,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      })
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.container {
}
</style>
